package com.dyx.source.bio;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;

/**
 * 为每个请求创建一个线程
 *
 * 要点：
 * 当一个连接对应一个线程时，线程一般采用「read -> 业务处理 -> send」的处理流程，如果当前连接没有数据可读，
 * 那么线程会阻塞在 read 操作上（ socket 默认情况是阻塞 I/O），不过这种阻塞方式并不影响其他线程。
 *
 *
 * @author dengyouxu
 * @date 2021.06.19 00:10:05:565
 */
public class MultiThreadBIOServer {
    private static final Logger LOGGER = LoggerFactory.getLogger(MultiThreadBIOServer.class);

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket();
            serverSocket.bind(new InetSocketAddress(2345));
        } catch (IOException ex) {
            LOGGER.error("Listen failed", ex);
            return;
        }
        try {
            while (true) {
                Socket socket = serverSocket.accept();
                new Thread(() -> {
                    try {
                        InputStream inputstream = socket.getInputStream();
                        LOGGER.info("Received message {}", StreamUtils.copyToString(inputstream, Charset.defaultCharset()));

                    } catch (IOException ex) {
                        LOGGER.error("Read message failed", ex);
                    }
                }).start();
            }
        } catch (IOException ex) {

            LOGGER.error("Accept connection failed", ex);
        }
    }
}